<template>
	<view class="container">
		<view class="item flex-row" @tap="changeConversation(item)" v-for="item in list" :key="item.id">
			<view class="">
				<xbc-avatar class="avatar" :src="item?.profile?.avatar" :group="item.type == 'group'" />
				<xbc-badge :count="item.unreadCount" />
			</view>
			<view class="info">
				<view class="flex-row">
					<view class="name">{{ item?.profile?.name }}</view>
					<view class="time">{{ item?.lastMessage?.createdAt }}</view>
				</view>
				<view class="message text-ellipsis">{{ item?.lastMessage?.contentText }}</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import { onShow, onHide, onLoad } from '@dcloudio/uni-app';
	import XBCIM from 'xbcim';

	const list = ref([]);

	// 获取会话列表
	async function getList() {
		list.value = await XBCIM.getConversationList()
	}

	// 获取会话未读数
	async function getUnreadCount() {
		const unreadCount = await XBCIM.getConversationUnreadCount() as number
		if (unreadCount > 0) {
			uni.setTabBarBadge({
				index: 0,
				text: unreadCount.toString()
			})
		} else {
			uni.removeTabBarBadge({
				index: 0
			})
		}
	}

	// 切换会话
	function changeConversation(conversation: any) {
		const { type, conversationId } = conversation
		uni.setStorageSync('currentConversation', conversation)
		uni.navigateTo({
			url: `/pages/chat/${type}?id=${conversationId}`
		})
	}

	onLoad(() => {
		// 监听收到消息
		XBCIM.on(XBCIM.EVENT.MESSAGE_RECEIVED, getUnreadCount)
	})

	onShow(() => {
		getList()
		getUnreadCount()

		// 监听会话列表更新
		XBCIM.on(XBCIM.EVENT.CONVERSATION_LIST_UPDATE, getList)
	})

	onHide(() => {
		// 取消监听会话列表更新
		XBCIM.off(XBCIM.EVENT.CONVERSATION_LIST_UPDATE, getList)
	})
</script>

<style lang="scss" scoped>
	.item {
		padding: 30rpx;
		justify-content: flex-start;
		border-bottom: 2rpx solid #f5f5f5;
		position: relative;

		.info {
			width: calc(100% - 120rpx);
			margin-left: 30rpx;

			.name {
				color: #333;
				font-size: 32rpx;
			}

			.time {
				color: #999;
				font-size: 28rpx;
			}

			.message {
				color: #666;
				font-size: 26rpx;
				margin-top: 12rpx;
			}
		}
	}
</style>